package com.zg.common.web.aop;

import cn.hutool.core.util.StrUtil;
import com.zg.common.core.User;
import com.zg.common.web.Req;
import com.zg.common.core.exception.E;
import com.zg.common.core.util.TokenUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Nonnull;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Token拦截器
 * @author Zxb
 */
@Component
@RequiredArgsConstructor
public class TokenInterceptor implements HandlerInterceptor {
    private static final String USER_FETCH_SQL = "select count(*) from auth_user where username = ?";
    private final JdbcTemplate jdbcTemplate;

    @Override
    public boolean preHandle(
            @Nonnull HttpServletRequest request,
            @Nonnull HttpServletResponse response,
            @Nonnull Object handler) {
        String token = Req.getToken();
//        if (StrUtil.isBlank(token)) {
//            E.NO_TOKEN.happen();
//            return false;
//        }
//        User u = TokenUtil.validateToken(token);
//        if (u == null) {
//            E.BAD_TOKEN.happen();
//            return false;
//        }
//        int count = jdbcTemplate.queryForObject(USER_FETCH_SQL, Integer.class, u.getUsername());
//        if (count == 0) {
//            E.NO_USER.happen();
//            return false;
//        }
        return true;
    }
}
